package com.eqdd.yiqidian.listener.rongyun;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.AppManager;
import com.eqdd.yiqidian.base.BaseApplication;
import com.eqdd.yiqidian.bean.LoginRecordBean;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.kotlin.net.HttpResult;
import com.eqdd.yiqidian.service.LocationObservable;
import com.eqdd.yiqidian.service.RongyunService;
import com.eqdd.yiqidian.utils.LogoutUtil;
import com.eqdd.yiqidian.utils.PreferenceUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import io.rong.imlib.RongIMClient;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by lvzhihao on 17-4-6.
 */

public class ConnectionStatusListener implements RongIMClient.ConnectionStatusListener {

    private String province = "未知";
    private String city = "未知";
    private String area = "未知";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA);


    @Override
    public void onChanged(ConnectionStatus connectionStatus) {

        switch (connectionStatus) {

            case CONNECTED://连接成功
                getLocation();
                Log.w("xxx", "链接成功");
                break;
            case DISCONNECTED://断开连接。
                Log.w("xxx", "断开链接");
                exitTime();
                break;
            case CONNECTING://连接中。
                Log.w("xxx", "连接中");
                break;
            case NETWORK_UNAVAILABLE://网络不可用。
                Log.w("xxx", "链接不可用");
                exitTime();
                break;
            case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线
                exitTime();
                System.out.println("用户账户在其他设备登录，本机会被踢掉线");
                AndroidSchedulers.mainThread().createWorker().schedule(() -> {
                    Activity activity = AppManager.getAppManager().currentActivity();
                    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    builder.setMessage("用户账户在其他设备登录");
                    builder.setTitle("下线通知");
                    builder.setCancelable(true);
                    builder.setPositiveButton("重新登陆", (dialog, which) -> {
                        dialog.dismiss();
                        activity.startService(new Intent(activity, RongyunService.class));

                    });
                    builder.setNegativeButton("退出", (DialogInterface dialog, int which) -> {
                                dialog.dismiss();
                                LogoutUtil.logout();
                            }
                    );
                    builder.create().show();
                });

                break;
        }
    }

    private void exitTime() {
        LoginRecordBean bean = PreferenceUtil.find(BaseApplication.context, AppConstent.LOGIN_RECORD, LoginRecordBean.class);
        if (bean == null) {
            Log.w("xxx", "xxxxxxxx");
            return;
        }
        Date date = new Date();
        String string = sdf.format(date);
        bean.setExitTime(string);
        PreferenceUtil.save(BaseApplication.context, bean, AppConstent.LOGIN_RECORD);
        exit();
    }

    private void getLocation() {
        RxPermissions.getInstance(AppManager.getAppManager().currentActivity()).request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(isGrant -> LocationObservable.get()
                        .subscribe(aMapLocation -> {
                                    if (aMapLocation.getErrorCode() == 0) {
                                        province = aMapLocation.getProvince();
                                        city = aMapLocation.getCity();
                                        area = aMapLocation.getDistrict();
                                    }
                                    login();
                                }
                        )
                );
    }

    private void login() {
        LoginRecordBean bean = PreferenceUtil.find(BaseApplication.context, AppConstent.LOGIN_RECORD, LoginRecordBean.class);
        if (bean != null && bean.getExitTime() != null) {
            exit();
        }
        if (AppConstent.user == null) return;
        OkGo.<HttpResult<Integer>>post(HttpConfig.BASE_URL + HttpConfig.RECORD_LOGIN)
                .params("userGuid", AppConstent.user.getGuid())
                .params("phone", AppConstent.user.getUname())
                .params("phoneModel", Build.MODEL)
                .params("province", province)
                .params("city", city)
                .params("area", area)
                .execute(new JsonCallBack<HttpResult<Integer>>() {
                    @Override
                    public void onSuccess(Response<HttpResult<Integer>> response) {
                        HttpResult<Integer> result = response.body();
                        if (result != null && result.getStatus() == 200) {
                            LoginRecordBean bean = new LoginRecordBean();
                            if (result.getItems() != null) {
                                bean.setLoginId(result.getItems());
                                PreferenceUtil.save(BaseApplication.context, bean, AppConstent.LOGIN_RECORD);
                            }
                        }
                    }
                });
    }

    private void exit() {
        LoginRecordBean bean = PreferenceUtil.find(BaseApplication.context, AppConstent.LOGIN_RECORD, LoginRecordBean.class);
        if (bean != null && AppConstent.user != null) {
            OkGo.<HttpResult<Integer>>post(HttpConfig.BASE_URL + HttpConfig.RECORD_EXIT)
                    .params("userGuid", AppConstent.user.getGuid())
                    .params("logId", bean.getLoginId())
                    .execute(new JsonCallBack<HttpResult<Integer>>() {
                        @Override
                        public void onSuccess(Response<HttpResult<Integer>> response) {
                            HttpResult<Integer> result = response.body();
                            if (result.getStatus() == 200) {
                                PreferenceUtil.delete(BaseApplication.context, AppConstent.LOGIN_RECORD, String.class);
                            }
                        }
                    });
        }

    }

}